'use strict';

//顶端查询组件,component中使用ng-include嵌套有bug改为directive
app.directive("headerSearch",['$document', function($document){
    return {
        restrict: 'E',
        scope:true,
        templateUrl: ISS.getResPath('app/headerSearch.html'),
        controller: ['$scope', '$element', '$attrs', '$rootScope', 'HeaderSearchService',
            function ($scope, $element, $attrs, $rootScope, HeaderSearchService) {

                var vm = $scope.vm = this;

                vm.selected = null;
                vm.levelObject = {};
                vm.search = {name:''};
                //选择地址
                vm.select = function(location){
                    var parentLevel = vm.levelObject['' + location.level];
                    if(ISS.isNotEmpty(location.children)){
                        parentLevel.name = location.name;
                    }else{
                        parentLevel.name = '';
                    }

                    var _level = location.level + 1;
                    vm.levelObject['' + _level] = {list: location.children};

                    var temp = {};
                    angular.forEach(vm.levelObject, function(value, key){
                        if(key <= _level){
                            temp[key] = value;
                        }
                    });
                    vm.levelObject = temp;

                    location.latitude = location.attrMap.latitude;
                    location.longitude = location.attrMap.longitude;

                    vm.selected = location;

                    vm.broadcast(vm.selected);
                    vm.searchFun();
                }
                //查询方法
                vm.searchFun = function(){
                    vm.search.archId = vm.selected.id;
                    HeaderSearchService.searchLocation(vm.search).then(function(data){
                        vm.searchList = data;
                    });
                }
                //选择查询的设备
                vm.selectSearch = function(location){
                    vm.broadcast(location);
                }

                vm.disabledSearch = function(){
                    return false;
                }

                $scope.$on('inited-notify-header',function(event){
                    vm.broadcast(vm.selected);
                });

                vm.broadcast = function(location){
                    $rootScope.$broadcast('header-location-change', location);
                }
                //查询地址列表信息
                HeaderSearchService.getTree().then(function(data){
                    vm.levelObject['1'] = {list: data.children};
                    if(ISS.isNotEmpty(data.children)){
                        vm.select(data.children[0]);
                    }
                });

            }]
    }
}]);

//地图经纬度选择组件
app.component('mapSelect', {
    bindings: {
        location:'=',
        onSelect:'='
    },
    controller: ['$scope','$element', '$attrs', 'dialogs', function(scope, el, attr, dialogs){
        var vm = scope.vm = this;
        var flag = attr["isMulti"];
        vm.setLocation = function(){
            var dlg = dialogs.create(
                ISS.getResPath('tpl/blocks/dlgs/latLanSelect-dlg.html'),
                'latLngSelectCtrl',
                {"flag": flag, "location": vm.location},
                // vm.location,
                {size:'lg', backdrop: false}
            );
            dlg.result.then(function(lngLat){
                if(vm.onSelect){
                    vm.onSelect(lngLat);
                }
            });
        }
    }],
    template:'<button class="btn btn-default" ng-click="vm.setLocation()" translate="common.location"></button>'
});

//无级调光组件
app.component('brightContrl', {
    bindings: {
        sensor:'=',
        start:'=',
        stop:'='
    },
    controller: ['$scope','$element', '$attrs', function(scope, el, attr){
        var vm = scope.vm = this;

        vm.sliderStart = function(){
            if(vm.start){
                vm.start();
            }
        }

        vm.sliderStop = function(event, ele, sensor){
            if(vm.stop){
                vm.stop(ele.value, sensor);
            }
        }
    }],
    template:'<div class="btn-group-xs dropdown" style="padding-left: 20px;" uib-dropdown auto-close="outsideClick">\n'+
    '<button class="btn btn-xs" uib-dropdown-toggle style="background: #fff;" ng-disabled="vm.sensor.onlineStatus == \'offLine\'">\n'+
    '  <i class="fa fa-adjust"></i> \n'+
    '</button>\n'+
    '<ul class="dropdown-menu" uib-dropdown-menu style="right: 0px; left: inherit; font-size:12px; padding: 8px 8px; cursor: auto;">\n'+
    ' <li>\n'+
    '  <div ui-slider="{orientation: \'horizontal\',model: vm.sensor, start: vm.sliderStart, stop: vm.sliderStop}"\n'+
    '  	 min="0" max="100" step="1" ng-model="vm.sensor.$brightness_" style="background-color: #d3d3d3;">\n'+
    '  </div>\n'+
    '  <div>\n'+
    '   <span style="float:left;">0</span>\n'+
    '   <span style="float:right;">100</span>\n'+
    '  </div>\n'+
    ' </li>\n'+
    '</ul>\n'+
    '</div>'
});

//无级调光组件
app.component('deviceGrid', {
    bindings: {
        onClick:'=',
        onCheck:'=',
        unInstall:'=',
        onIconClick:'='
    },
    controller: ['$scope','$element', '$attrs','dialogs','$q', 'DeviceService', function($scope, el, attr,dialogs,$q, DeviceService){
        var vm = $scope.vm = this;

        vm.pager = {rp:10, page:1};
        vm.condition = null;

        //通过条件查询设备
        var queryDeviceByCondition = function(location) {
            if(vm.unInstall){
                //查询未安装的设备列表
                DeviceService.unInstallList().then(function(list){
                    vm.unInstallList = list;
                });
            }
            vm.queryDevice(location);
        }
        //显示关闭未安装列表
        vm.showUninstallDevice = function(pageData){
            if (pageData.showDevice) {
                pageData.showDevice = false;
            } else {
                pageData.showDevice = true;
            }
        }
        //查询已安装的设备列表
        vm.queryDevice = function(condition){
            if(ISS.isNotEmpty(condition)){
                vm.condition = condition;
            }else{
                condition = vm.condition;
            }
            var param = angular.copy(vm.pager);
            if(ISS.isNotEmpty(condition)){
                param.condition = {archId: condition.archId};
                if(condition.type != 1){
                    param.condition.gatewayId = condition.gatewayId;
                }
            }
            DeviceService.getInstalledList(param).then(function(data){
                if (data.total) {
                    vm.pager.total = data.total;
                }
                vm.installedList = data.rawRecords;//设备列表
                vm.device = null;
            });
        }

        //获取设备图标
        vm.getDeviceIcon = function(device){
            var style = ISS.getDeviceIcon(device.deviceTypeId);
            if(vm.onIconClick){
                style['c-p'] = true;
            }
            return style;
        }
        vm.iconClick = function(device){
            if(vm.onIconClick){
                vm.onIconClick(device);
            }
        }
        vm.getUpdateDate = function(date){
            if(ISS.isEmpty(date)){
                date = new Date();
            }

            return moment(date).format('MM-dd HH:mm')
        }
        //查询网关下的设备列表,isRefresh是否为刷新传感器列表
        vm.openSensorList = function(device, isRefresh){
            if(!isRefresh){
                device.$sensorListIsOpened_ = !device.$sensorListIsOpened_;
            }
            if(!device.sensorList || isRefresh){
                if(device.deviceTypeId != 1){
                    //设备本身
                    device.updated = vm.getUpdateDate();
                    if(ISS.isNotEmpty(device.switchStatus)){
                        device.$switchStatus_ = device.switchStatus;
                    }
                    device.sensorList = [angular.copy(device)];
                }else{
                    //查询网关下的设备
                    DeviceService.getSensors({gatewayId: device.gatewayId}).then(function(data){
                        angular.forEach(data.rawRecords, function(sensor){
                            sensor.updated = vm.getUpdateDate();
                            if(ISS.isNotEmpty(sensor.switchStatus)){
                                sensor.$switchStatus_ = sensor.switchStatus;
                            }
                        });
                        device.sensorList = data.rawRecords;
                        if(device.sensorId){
                            angular.forEach(data.rawRecords, function(obj){
                                if(device.sensorId == obj.sensorId) {
                                    angular.extend(device,obj);
                                    return;
                                }
                            });
                        }
                    });
                }
            }
        }
        //显示关闭查询传感器数值
        vm.getSensorProperty = function(sensor){
            if(sensor){
                sensor.$openDataRow_ = !sensor.$openDataRow_;
            }
        }
        //勾选设备
        var _checkedSensorList = [];
        //全选设备
        vm.checkAllSensor = function(gw){
            _checkedSensorList = [];

            angular.forEach(vm.installedList, function(gw){
                angular.forEach(gw.sensorList, function(sensor){
                    sensor.$checked_ = gw.$checkAll_;
                    if(gw.$checkAll_){
                        _checkedSensorList.push(sensor);
                    }
                });
            });
        }
        //单选设备
        vm.checkSensor = function(gw, se){
            var isAllChecked = true;
            _checkedSensorList = [];

            angular.forEach(vm.installedList, function(gw){
                angular.forEach(gw.sensorList, function(sensor){
                    if(!sensor.$checked_){
                        isAllChecked = false;
                    }else{
                        _checkedSensorList.push(sensor);
                    }
                });
                if(ISS.isEmpty(gw.sensorList)){
                    gw.$checkAll_ = false;
                }else{
                    gw.$checkAll_ = isAllChecked;
                }
            });
        }

        var currentSelect = null;
        //安装配置
        vm.install = function(device, type){
            if(currentSelect){
                currentSelect.selected = false;
            }
            device.selected = true;
            currentSelect = device;
            vm.device=device;

            angular.forEach(_checkedSensorList, function(sensor){
                sensor.$checked_ = false;
            });

            vm.selectType = "single";
            if(device.delFlag == 0){
                //已安装修改
                var param = angular.copy(device);
                DeviceService.getSensor(param.deviceId).then(function(sensor){
                    angular.extend(currentSelect, sensor);
                    vm.device = currentSelect;
                    //把选择到的设备传给SensorCtrl
                    if(vm.onClick){
                        vm.onClick(device, 'edit');
                    }
                });
            }else{
                //未安装
                DeviceService.getSensor(device.deviceId).then(function(sensor){
                    vm.device = sensor;
                    //把选择到的设备传给SensorCtrl
                    if(vm.onClick){
                        vm.onClick(device, 'add');
                    }
                });
            }
        }
        //双灯选择
        vm.doubleSwitch = function(sensorList, deviceType,status){
            var tempList = [];
            if(tempList.length != 0){
                DeviceService.changeBright(tempList, status);
            }
        }

        //设置开关
        vm.sensorSwitch = function(sensorList, status){
            var tempList1 = [];
            var tempList2 = [];
            var switchstatus = [];
            switchstatus.push(status);
            switchstatus.push(status);
            if(ISS.isEmpty(sensorList)){
                angular.forEach(_checkedSensorList, function(sensor,index){
                    sensorList.push(sensor);
                });
            }
            angular.forEach(sensorList, function(sensor,index){
                if(sensor.onlineStatus == 'onLine')
                {
                    if(sensor.deviceTypeId == 24){
                        tempList1.push(sensor);
                    }
                    if(sensor.deviceTypeId == 25){
                        tempList2.push(sensor);
                    }
                }
            });
            if(tempList1.length != 0){
                DeviceService.changeBright(tempList1, status);
            }
            if(tempList2.length != 0){
                DeviceService.changeBright(tempList2, switchstatus);
            }
        }

        //刷新所有
        vm.refreshAll = function(){
            queryDeviceByCondition();
        }

        //无极调光 批量
        vm.brightnessMulti = function(event,ele,sensorList){
            var brightness = ele.value;
            var tempList1 = [];
            var tempList2 = [];
            var bright = [];
            bright.push(brightness);
            bright.push(brightness);
            if(ISS.isEmpty(sensorList)){
                angular.forEach(_checkedSensorList, function(sensor,index){
                    sensorList.push(sensor);
                });
            }
            angular.forEach(_checkedSensorList, function(sensor,index){
                if(sensor.onlineStatus == 'onLine')
                {
                    if(sensor.deviceTypeId == 24){
                        tempList1.push(sensor);
                    }
                    if(sensor.deviceTypeId == 25){
                        tempList2.push(sensor);
                    }
                }
            });
            if(tempList1.length != 0){
                DeviceService.changeBright(tempList1, brightness);
            }
            if(tempList2.length != 0){
                DeviceService.changeBright(tempList2, bright);
            }
        }
        //无极调光 单调
        vm.brightnessSingle = function(value, se){
            var brightness = value;
            var sensorList = [se];

            DeviceService.changeBright(sensorList, brightness);
        }

        vm.sliderStop = function(event, ele, sensor){
            if(vm.lightSelect.join('') == "00")
            {
                dialogs.notify(getMessage("device.unSelected"));
                var deferred = $q.defer();
                deferred.resolve(false);
                return deferred.promise;
            }
            var value = ele.value;
            var brightness = [0,0];
            angular.forEach(vm.lightSelect,function(select,index){
                if(select == 1)
                {
                    brightness[index] = value;
                    sensor.switchStatus[index].$Check_ = false;
                }else{
                    brightness[index] = -1;
                }
            });
            vm.lightSelect = [0,0];
            DeviceService.changeBright([sensor], brightness, true);
        }
        //双灯开关控制
        vm.lightSelect = [0,0];
        vm.lightflag = null;
        vm.lightCheck = function(switchStatus){
            vm.lightflag = null;
            angular.forEach(switchStatus,function(value,index){
                if(value.$Check_){
                    vm.lightSelect[index] = 1;
                }else{
                    vm.lightSelect[index] = 0;
                }
            });
        }
        vm.LightSwitch = function(sensor,status){
            if(vm.lightSelect.join('') == "00")
            {
                dialogs.notify(getMessage("device.unSelected"));
                var deferred = $q.defer();
                deferred.resolve(false);
                return deferred.promise;
            }
            var switchStatus = ['close','close'];
            angular.forEach(vm.lightSelect,function(value,index){
                if(value == 1)
                {
                    switchStatus[index] = status;
                    sensor.switchStatus[index].$Check_ = false;
                }else{
                    switchStatus[index] = false;
                }
            });
            vm.lightSelect = [0,0];
            DeviceService.changeBright([sensor], switchStatus, true);
        }

        //设备状态改变时，接收到广播数据后
        $scope.$on('device-data-change', function(event, data) {
//	    	$scope.doubleSensorSwitch = '';
            var index1 = DeviceService.gatewayIndexObj[data.gatewayId];
            var gateway = vm.installedList[index1];
            if(ISS.isNotEmpty(gateway))
            {
                var index2 = DeviceService.sensorIndexObj[data.sensorId];
                if(ISS.isNotEmpty(gateway.sensorList)){
                    var sensor = gateway.sensorList[index2];
                    if(data.sensorId == sensor.sensorId) {
                        sensor.updated = moment(new Date()).format('MM-dd HH:mm');
                        angular.extend(sensor, data);

                        if(null != vm.device)
                        {
                            angular.extend(vm.device, data);
                        }
                    }
                }
            }

        });

        //列表刷新事件
        $scope.$on('list-refresh', function(event, type){
            if(type == 'refreshSensors'){
                //刷新网关的传感器列表
                vm.getSensors(currentSelect, true);
            }else{
                //刷新所有列表
                vm.refreshAll();
            }
        });
        $scope.$on('header-location-change', function(event, location){
            if(location){
                var archId = location.id;
                if(location.archId != null)
                {
                    archId = location.archId;
                }
                queryDeviceByCondition({'archId':archId});
            }
        });
        //初始化完成后查询
        vm.$onInit = function(){
            //queryDeviceByCondition();
        }
    }],

    templateUrl:'tpl/blocks/device/list.html'
});

//无级调光组件
app.component('alarmToaster', {
    bindings: {
        sensor:'=',
        start:'=',
        stop:'='
    },
    controller: ['$scope','$element', '$attrs','$interval','$timeout','DeviceService',
        function(scope, el, attr,$interval,$timeout, DeviceService){
            var vm = scope.vm = this;

            vm.alarms = [];
            vm.activeIndex = 0;
            vm.getAlarms = function(){
                $timeout(function(){
                    DeviceService.getAlarms().then(function(data){
                        vm.alarms = data;
                        //
                        vm.getAlarms();
                    })
                }, 1000*60);
            }

            $interval(function(){
                angular.forEach(vm.alarms, function(alarm, index){
                    alarm.$active_ = false;
                });
                if(ISS.isNotEmpty(vm.alarms)){
                    if(vm.activeIndex < vm.alarms.length-1){
                        vm.activeIndex++;
                    }else{
                        vm.activeIndex = 0;
                    }
                    vm.alarms[vm.activeIndex].$active_ = true;
                }
            }, 3000);

            vm.$onInit = function(){
                vm.getAlarms();
            }
        }],
    template:'<div class="pos-fix text-2x text-center alarmToaster" ng-hide="app.isEmpty(vm.alarms)" style="">'+
    '<div ng-repeat="a in vm.alarms track by a.alarmId" class="item" ng-class="{active: a.$active_}">'+
    '<p>{{a.deviceId}} {{("alarm." + a.category) | translate}}</p>'+
    '</div>'+
    '</div>'
});
